package org.dtrd.modules.content.articles.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.dto.BaseRecordRequest;
import org.dtrd.common.api.dto.DetailRequest;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.aspect.annotation.AutoLog;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.config.system.SystemState.ResponseState;
import org.dtrd.modules.content.articles.entity.bean.*;
import org.dtrd.modules.content.articles.entity.po.DtrdExtEmsContent;
import org.dtrd.modules.content.articles.entity.po.DtrdExtEmsYwCheckList;
import org.dtrd.modules.content.articles.entity.po.DtrdExtEmsYwWords;
import org.dtrd.modules.content.articles.entity.request.*;
import org.dtrd.modules.content.articles.entity.vo.DtrdExtEmsYwFaqsVO;
import org.dtrd.modules.content.articles.service.*;
import org.dtrd.modules.faq.service.IDtrdExtEmsYwFaqsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_QUERY;

/**
 * 知识百科
 *
 * @author 萧
 * @date:2021-08-25 9:50 下午
 **/
@RestController
@Slf4j
@Api(tags = "知识百科")
@ApiSort(10)
@RequestMapping("/article")
public class ArticleController extends BaseController {

    @Autowired
    private IDtrdExtEmsCategoryService categoryService;
    @Autowired
    private IDtrdExtEmsContentService contentService;
    @Autowired
    private IDtrdExtEmsYwFaqsService faqsService;
    @Autowired
    private IDtrdExtEmsYwCheckListCategoryService checkListCategoryService;
    @Autowired
    private IDtrdExtEmsYwCheckListService checkListService;
    @Autowired
    private IDtrdExtEmsYwWordsService wordsService;
    @Autowired
    private IDtrdExtEmsFaqCategoryService faqCategoryService;

    @ApiOperation("文章子分类与分类下文章数")
    @GetMapping(path = {"/category/{classId}", "/category"})
    public Result<?> getArticleCategory(@PathVariable(required = false) Integer classId) {
        if (classId == null) {
            // 默认查询用户端文章分类
            classId = 15;
        }
        if (isIntParamInvalid(classId)) {
            return error(ResponseState.STATE_PARAMS_MISSING);
        }
        List<ArticleCategory> list = categoryService.selectCategoryAndArticleCount(classId);
        return Result.OK(list);
    }

    @ApiOperation("文章分类")
    @GetMapping(path = {"/category/all/{classId}", "/category/all"})
    public Result<?> getAllArticleCategory(@PathVariable(required = false) Integer classId) {
        List<ArticleCategory> list = categoryService.getAllCategory(classId);
        return Result.OK(list);
    }

    @ApiOperation("管理文章分类")
    @PostMapping("/category/manage")
    public Result<?> addOrEditArticleCategory(@RequestBody EditArticleCategoryRequest request) {
        if (StringUtils.isEmpty(request.getCategoryName())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        if (StringUtils.isEmpty(request.getCategoryIcon())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        boolean result = categoryService.addOrEditArticleCategory(request);
        return result ? Result.OK() : error(ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation("删除文章分类")
    @GetMapping("/category/delete/{classId}")
    public Result<?> deleteArticleCategory(@PathVariable Integer classId) {
        if (isIntParamInvalid(classId)) {
            return error(ResponseState.STATE_PARAMS_MISSING);
        }
        categoryService.deleteArticleCategory(classId);
        return Result.OK();
    }

    @ApiOperation("文章列表")
    @PostMapping("/list")
    public Result<?> getArticleList(@RequestBody ArticlePageRequest request) {
        Integer pageNum = getIntParam(request.getPageNum(), 1);
        Integer pageSize = getPageSize(request.getPageSize(), Constant.PAGESIZE);
        IPage<DtrdExtEmsContent> list = contentService.getArticleList(pageNum, pageSize, request.getArticleCategory(), request.getTitle(), request.getKeyword());
        return Result.OK(list);
    }

    @ApiOperation(value = "文章详情", response = ArticleInfo.class)
    @PostMapping("/detail")
    public Result<?> getArticleInfo(@RequestBody DetailRequest request) {
        if (request == null || request.getDataId() == null || request.getDataId() < 1) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        ArticleInfo info = contentService.getArticleInfoById(request.getDataId());
        if (info != null) {
            info.setContent(StringEscapeUtils.unescapeHtml(info.getContent()));
            return Result.OK(info);
        } else {
            return error(SystemState.ResponseState.STATE_PARAMS_ERROR);
        }
    }

    @ApiOperation("编辑文章详情")
    @PostMapping("/detail/manage")
    public Result<?> manageArticleInfo(@RequestBody ArticleInfo info) {
        if (isIntParamInvalid(info.getClassId())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        contentService.manageArticle(info);
        return Result.OK();
    }

    @ApiOperation("删除文章")
    @GetMapping("/detail/delete/{articleId}")
    public Result<?> deleteArticle(@PathVariable Integer articleId) {
        if (isIntParamInvalid(articleId)) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        contentService.deleteArticle(articleId);
        return Result.OK();
    }

    @ApiOperation(value = "文章推荐", response = ArticleRecommend.class)
    @PostMapping("/recommend/list")
    @AutoLog(value = "文章推荐", operateType = OPERATE_TYPE_QUERY)
    public Result<ArticleRecommend> getGroupRecommendArticleList() {
        List<GroupItem<String, ArticleInfo>> list = contentService.getGroupRecommendArticleList();
        ArticleRecommend recommend = new ArticleRecommend();
        recommend.setArticleList(list);
        // 固定查询最近三条记录
        List<FaqInfo> faqInfos = faqsService.getLatestRecords(3);
        recommend.setQuestionList(faqInfos);
        return Result.OK(recommend);
    }

    @ApiOperation("宜忌分类")
    @RequestMapping(value = "/check/category", method = RequestMethod.GET)
    public Result<?> getCheckCategory() {
        List<CheckCategory> list = checkListCategoryService.selectCategories();
        return Result.OK(list);
    }

    @ApiOperation("宜忌列表")
    @RequestMapping(value = "/check/list", method = RequestMethod.POST)
    public Result<IPage<DtrdExtEmsYwCheckList>> getCheckList(@RequestBody CheckPageRequest request) {
        Integer pageNum = getIntParam(request.getPageNum(), 1);
        Integer pageSize = getPageSize(request.getPageSize(), Constant.PAGESIZE);
        IPage<DtrdExtEmsYwCheckList> list = checkListService.getCheckList(pageNum, pageSize, request.getCheckCategory(), request.getCheckStatus());
        return Result.OK(list);
    }

    @ApiOperation("详情查询")
    @RequestMapping(value = "/check/desc", method = RequestMethod.POST)
    public Result<?> getCheckDesc(@RequestBody CheckDescRequest request) {
        CheckInfo checkInfo = checkListService.getCheckDesc(request.getDataId());
        return Result.OK(checkInfo);
    }

    @ApiOperation(value = "专业词汇列表", response = Vocabulary.class)
    @PostMapping("/word/list")
    public Result<?> getProfessionVocabularyList() {
        List<Vocabulary> list = wordsService.getWordList(null);
        return Result.OK(list);
    }

    @ApiOperation(value = "专业词汇字母分组列表")
    @PostMapping("/word/grouplist")
    public Result<List<GroupItem<Character, Vocabulary>>> getGroupVocabularyList(@RequestBody VocabularyRequest request) {
        List<GroupItem<Character, Vocabulary>> list = wordsService.getGroupWordList(request.getKeyWord());
        return Result.OK(list);
    }

    @ApiOperation(value = "专业词汇详情", response = Vocabulary.class)
    @PostMapping("/word/detail")
    public Result<?> getProfessionVocabularyInfo(@RequestBody BaseRecordRequest request) {
        DtrdExtEmsYwWords po = wordsService.getById(request.getDataId());
        return po == null ? error(ResponseState.STATE_NO_RECORD) : Result.OK(new Vocabulary(po));
    }

    @ApiOperation("知识问答分类")
    @RequestMapping(value = "/faq/category", method = RequestMethod.GET)
    public Result<List<FaqCategory>> getFaqsCategory() {
        Result<List<FaqCategory>> result = new Result<>();
        List<FaqCategory> list = faqCategoryService.selectCategories();
        result.setSuccess(true);
        log.info("ArticleController.getFaqCategory.[]");
        result.setResult(list);
        return result;
    }

    @ApiOperation("知识问答列表")
    @RequestMapping(value = "/faq/list", method = RequestMethod.POST)
    public Result<IPage<DtrdExtEmsYwFaqsVO>> getFaqList(@RequestBody FaqPageRequest request) {
        Result<IPage<DtrdExtEmsYwFaqsVO>> result = new Result<>();
        Integer pageNum = getIntParam(request.getPageNum(), 1);
        Integer pageSize = getPageSize(request.getPageSize(), Constant.PAGESIZE);
        IPage<DtrdExtEmsYwFaqsVO> list = faqsService.getFaqList(pageNum, pageSize, request.getFaqCategoryId());
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    /**
     * 知识问答详情
     *
     * @param id
     * @return
     */
    @ApiOperation("知识问答详情")
    @RequestMapping(value = "/faq/info/{id}", method = RequestMethod.GET)
    public Result<FaqInfo> getFagInfo(@PathVariable Integer id) {
        Result<FaqInfo> result = new Result<>();
        FaqInfo faqInfo = faqsService.getFagInfoById(id);
        result.setSuccess(true);
        result.setResult(faqInfo);
        return result;
    }
}
